package com.zhenwei.zscm.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;

@RestController
@RequestMapping("/api/captcha")
public class CaptchaController {
    @Autowired
    private DefaultKaptcha captchaProducer;

    // 更新生成验证码的部分，保存验证码文本到session
    @GetMapping("/generate")
    public void generateCaptcha(HttpServletResponse response, HttpSession session) throws IOException {
        // 禁止缓存
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);

        String captchaText = captchaProducer.createText();
        session.setAttribute("CAPTCHA_TEXT", captchaText);// 生成验证码图片
        BufferedImage captchaImage = captchaProducer.createImage(captchaText);
        // 设置响应类型为图像
        response.setContentType("image/jpeg");
        // 将图像写入响应输出流
        ImageIO.write(captchaImage, "JPEG", response.getOutputStream());
    }
}
